<template>
  <div class="com-container">
    <div class="search-box">
      <el-autocomplete
        class="inline-input"
        v-model="state"
        :fetch-suggestions="querySearch"
        placeholder="请输入人物名"
        :trigger-on-focus="false"
        @select="handleSelect"
        prefix-icon="el-icon-search"
      ></el-autocomplete>
    </div>
  </div>

</template>

<script>
import search from '@/api/search/search'

export default {
  data () {
    return {
      figureId: '',
      names:[],
      state:''
    }
  },
  methods: {
    querySearch (queryString, cb) {
      search.getFuzzyNames(queryString).then(res => {
        var names = res.data.names
        console.log(names)
        this.names = names
        // var restaurants = this.restaurants;
        // var results = queryString ? names.filter(this.createFilter(queryString)) : names;
        // 调用 callback 返回建议列表的数据
        const results = []
        names.forEach(item => {
          results.push({ value: item.figureName })
        })
        cb(results)
      })

    },
    createFilter (queryString) {
      return (names) => {
        return (names.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect (item) {
      // console.log(item)
      this.state = item.value
      const name = item.value
      const names = this.names
      for (let i = 0; i <names.length ; i++) {
        if(names[i].figureName === name){
          this.figureId = names[i].id
          break
        }
      }
      // console.log(this.figureId)
      if(this.figureId){
        this.$router.push({ path: "/figure/" + this.figureId });
      }
    },
  },
}
</script>

<style>

.search-box {
  text-align: center;
  background-color: #fff;
  border-radius: 20px;
  position: absolute;
  top: 10px;
  left: 10px;
  /*width: 20%;*/
  /*left: 50%;*/
  /*top: 50%;*/
  /*transform: translate(-50%,-50%);*/
}

.el-autocomplete{
/*text-align: center;*/
  width: 100%;
}


</style>
